/*
* Copyright (c) 2016 ShopJsp. All Rights Reserved.
 * ============================================================================
 * 版权所有 2011 - 今 北京华宇盈通科技有限公司，并保留所有权利。
 * ----------------------------------------------------------------------------
 * 提示：在未取得SHOPJSP商业授权之前，您不能将本软件应用于商业用途，否则SHOPJSP将保留追究的权力。
 * ----------------------------------------------------------------------------
 * 官方网站：http://www.shopjsp.com
 * ============================================================================
*/
package com.hyyt.shopjsp.basic.service.imp;

import com.hyyt.shopjsp.basic.dao.BasicPurviewDAO;
import com.hyyt.shopjsp.basic.pojo.BasicActor;
import com.hyyt.shopjsp.basic.pojo.BasicActorPurview;
import com.hyyt.shopjsp.basic.pojo.BasicPurview;
import com.hyyt.shopjsp.basic.pojo.BasicUsers;
import com.hyyt.shopjsp.basic.service.IBasicActorPurviewService;
import com.hyyt.shopjsp.basic.service.IBasicActorService;
import com.hyyt.shopjsp.basic.service.IBasicPurviewService;
import com.hyyt.shopjsp.basic.service.IBasicUsersService;
import com.hyyt.shopjsp.util.common.ResultMsg;
import com.hyyt.shopjsp.util.common.StringStaticKey;
import com.hyyt.shopjsp.util.common.Utils;
import com.hyyt.shopjsp.util.json.FastJsonUtils;
import com.hyyt.shopjsp.util.redis.service.IRedisBasicService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * basic_purview, BASIC_权限表
 *
 * @author Robot 14-5-7 上午10:19
 */
@Service
public class BasicPurviewService implements IBasicPurviewService {
    private static final Logger logger = Logger.getLogger(IBasicPurviewService.class);

    @Resource
    private BasicPurviewDAO basicPurviewDAO;
    @Resource
    private IBasicActorService basicActorService;
    @Resource
    private IRedisBasicService redisBasicService;
    @Resource
    private IBasicUsersService basicUsersService;
    @Resource
    private IBasicActorPurviewService basicActorPurviewService;

    /**
     * 保存BASIC_权限表
     *
     * @param basicPurview BASIC_权限表
     * @return 保存后的BASIC_权限表
     */
    @Override
    public ResultMsg saveBasicPurview(BasicPurview basicPurview, BasicUsers basicUsers) {
        if(Utils.objectIsNotEmpty(basicPurview)){
            if (Utils.objectIsNotEmpty(basicPurview.getPurviewId())) { //修改权限信息
                basicPurviewDAO.update(basicPurview);
            }else {//新建权限
                BasicPurview parentPurview = basicPurviewDAO.load(basicPurview.getParentId());
                if(Utils.objectIsNotEmpty(parentPurview)){
                    if (parentPurview.getIsLeaf().compareTo(0) != 0) {
                        parentPurview.setIsLeaf(0);
                        basicPurviewDAO.update(parentPurview);   //修改父节点为非子节点
                    }
                    basicPurview.setLevelCode(parentPurview.getLevelCode() + 1);
                    if(Utils.objectIsEmpty(basicPurview.getPurviewValidateCode())){//当前菜单节点为1级或者2级，页面中没有填写此编码为空
                        basicPurview.setPurviewValidateCode("#");
                    }
                }else{
                    basicPurview.setParentId(0);
                    basicPurview.setLevelCode(1);
                    basicPurview.setPurviewValidateCode("#");
                }
                basicPurview.setIsLeaf(1);  //肯定是叶子节点
                basicPurviewDAO.insert(basicPurview);    //保存此权限

                //绑定此权限到当前登录用户对应的角色中，但是功能权限没有被对应起来，只有菜单权限
           /* List<BasicActor> basicActors = basicActorService.queryAllBasicActorByUsersId(basicUsers.getUsersId());
                if (Utils.objectIsNotEmpty(basicActors) && basicActors.size() > 0) {
                    for (BasicActor actor : basicActors) {
                        BasicActorPurview actorPurview = new BasicActorPurview();
                        actorPurview.setActorId(actor.getActorId());    //角色ID
                        actorPurview.setPurviewId(basicPurview.getPurviewId()); //新生成的权限id
                        basicActorPurviewService.saveBasicActorPurview(actorPurview);
                    }
                }*/
            }
        }

        if (Utils.objectIsNotEmpty(basicPurview.getPurviewId())) {
            //this.updateRedisOfUserPurview(basicUsers); //同步用户权限到redis
            return new ResultMsg(true);
        }else {
            return new ResultMsg(false);
        }
    }

    /**
     * 更新BASIC_权限表
     *
     * @param basicPurview BASIC_权限表
     * @return 更新后的BASIC_权限表
     */
    @Override
    public void updateBasicPurview(BasicPurview basicPurview) {
        basicPurviewDAO.update(basicPurview);
        //initFilterChain();  //重新初始化Shiro的URL拦截器链
    }

    /**
     * 删除指定ID的BASIC_权限表
     *
     * @param purviewId BASIC_权限表ID
     */
    @Override
    public ResultMsg deleteBasicPurview(BasicUsers basicUsers, Integer purviewId) {
        ResultMsg result = new ResultMsg(false);
        if (Utils.objectIsNotEmpty(purviewId)) {
            //获取当前权限对象
            BasicPurview purview = basicPurviewDAO.load(purviewId);
            if (Utils.objectIsNotEmpty(purview)) {
                //查询并删除此权限与角色关联关系
                basicPurviewDAO.delete(purviewId); //删除当前权限
                //统计与此权限同级权限的数量
                Map<String, Object> param = new HashMap<>();
                List<BasicActor> basicActors = basicActorService.queryAllBasicActorByUsersId(basicUsers.getUsersId());
                param.put("purviewId", purviewId);
                if (Utils.objectIsNotEmpty(basicActors) && basicActors.size() > 0) {
                    for (BasicActor actor : basicActors) {
                        param.put("actorId", actor.getActorId());
                        List<BasicActorPurview> basicActorPurviews = basicActorPurviewService.queryBasicActorPurview(param);
                        basicActorPurviewService.deleteBasicActorPurview(actor.getActorId(),purviewId);
                    }
                }
                param.clear();
                param.put("parentId", purview.getParentId());
                int count = this.countBasicPurview(param);
                //判断此权限是否有兄弟，等于1 即没有兄弟，那么父节点权限即成为叶子节点
                if (count == 0) {
                    BasicPurview basicPurview = basicPurviewDAO.load(purview.getParentId());
                    basicPurview.setIsLeaf(1);  //改为叶子节点
                    basicPurviewDAO.update(basicPurview);
                }
                //更新当前用户权限redis缓存
                //this.updateRedisOfUserPurview(basicUsers);
                result.setSuccess(true);
            } else {
                result.setMsg("您操作的权限已不存在");
            }
        } else {
            result.setMsg("无法获得权限id，请重新操作");
        }
        return result;
    }

    /**
     * 删除指定ID集合的BASIC_权限表
     *
     * @param ids BASIC_权限表ID集合
     */
    public void deleteBasicPurview(Collection<Integer> ids) {
        basicPurviewDAO.batchDelete(ids);
        //initFilterChain();  //重新初始化Shiro的URL拦截器链
    }

    /**
     * 根据ID加载一个BASIC_权限表
     *
     * @param id BASIC_权限表ID
     * @return BASIC_权限表
     */
    @Override
    public BasicPurview loadBasicPurview(Integer id) {
        return basicPurviewDAO.load(id);
    }

    /**
     * 查询所有的BASIC_权限表，通常有最多取30000条记录的限制
     *
     * @return 所有的BASIC_权限表，通常有最多取30000条记录的限制
     */
    @Override
    public List<BasicPurview> queryAllBasicPurview() {
        return basicPurviewDAO.queryAll();
    }

    /**
     * 查询所有的BASIC_权限表，通常有最多取30000条记录的限制
     * params 查询系列参数
     * @return 所有的BASIC_权限表，通常有最多取30000条记录的限制
     */
    @Override
    public List<BasicPurview> queryAllBasicPurviewByMap(Map<String, Object> params) {
        return basicPurviewDAO.query("getNodes",params);
    }

    /**
     * 查询BASIC_权限表
     *
     * @param params 查询参数，为key-value形式
     * @return BASIC_权限表集合
     */
    @Override
    public List<BasicPurview> queryBasicPurview(Map<String, Object> params) {
        return basicPurviewDAO.query(params);
    }

    /**
     * 查询BASIC_权限表
     *
     * @param params   查询参数，没有则传null,分页参数key为“sortColumns”
     * @param startRow 起始行数（不含起始行的数据）
     * @param rowSize  要查询记录数
     * @return BASIC_权限表集合
     */
    @Override
    public List<BasicPurview> queryBasicPurview(Map<String, Object> params, int startRow, int rowSize) {
        return basicPurviewDAO.query(params, startRow, rowSize);
    }

    /**
     * 自定义查询BASIC_权限表
     *
     * @param params   查询参数，没有则传null,分页参数key为“sortColumns”
     * @param startRow 起始行数（不含起始行的数据）
     * @param rowSize  要查询记录数
     * @return BASIC_权限表集合
     */
    @Override
    public List<Map<String, Object>> queryBasicPurviewAndFunctions(Map<String, Object> params, int startRow, int rowSize) {
        return basicPurviewDAO.query("query_bps",params, startRow, rowSize);
    }

    /**
     * 自定义统计BASIC_权限表
     *
     * @param params 查询参数，没有则传null,分页参数key为“sortColumns”
     * @return 结果集记录数
     */
    @Override
    public int countBasicPurviewAndFunctions(Map<String, Object> params) {
        return basicPurviewDAO.count("count_bps",params);
    }

    /**
     * 统计BASIC_权限表
     *
     * @param params 查询参数，没有则传null,分页参数key为“sortColumns”
     * @return 结果集记录数
     */
    @Override
    public int countBasicPurview(Map<String, Object> params) {
        return basicPurviewDAO.count(params);
    }

    /**
     * 根据角色id获得所有权限
     *
     * @param actorId
     * @return
     */
    @Override
    public List<BasicPurview> queryBasicPurviewByActorId(Integer actorId) {
        Map<String, Object> params = new HashMap<>();
        params.put("actorId", actorId);
        params.put("sortColumns", "sortCode asc");
        return basicPurviewDAO.query("queryBasicPurviewByActorId", params);
    }

    /**
     * 根据用户名称更新用户权限到redis
     *
     * @param basicUsers
     */
    @Override
    public void updateRedisOfUserPurview(BasicUsers basicUsers) {
        if (Utils.objectIsNotEmpty(basicUsers)) {
            //查询出用户的所有角色
            List<BasicActor> basicActors = basicActorService.queryAllBasicActorByUsersId(basicUsers.getUsersId());
            if (Utils.objectIsNotEmpty(basicActors) && basicActors.size() > 0) {

                List<BasicPurview> basicPurviews = new ArrayList<>();
                for (BasicActor actors : basicActors) {
                    basicPurviews.addAll(actors.getBasicPurviews());
                }
                redisBasicService.setKey(StringStaticKey.PURVIEW_USER_PREFIX + basicUsers.getUserName(), FastJsonUtils.toJSONString(basicPurviews));
            }
        }
        //initFilterChain();  //重新初始化Shiro的URL拦截器链
    }

    /**
     * 取出角色权限关系集合中的主键id
     * @param list
     * @return
     */
    private List<Integer> basicActorPurviews2Integers(List<BasicActorPurview> list) {
        List<Integer> ints = new ArrayList<>();
        if (Utils.objectIsNotEmpty(list) && list.size() > 0) {
            for (BasicActorPurview actorpurview : list) {
                ints.add(actorpurview.getActorPurviewId());
            }
        }
        return ints;
    }

    /**
     * 统计指定分类下的叶子节点
     *
     * @param params 查询参数，没有则传null,分页参数key为“sortColumns”
     * @return 结果集记录数
     */
    @Override
    public int countIsLeafBasicPurview(Map<String, Object> params) {
        Integer parentId=Integer.parseInt(params.get("parentId").toString());
        BasicPurview bp=basicPurviewDAO.load(parentId);
        if(Utils.objectIsNotEmpty(bp)){
            Integer levelCode=bp.getLevelCode();
            if(levelCode==1){//查看一级菜单中所有的二级菜单下的三级菜单列表
                return basicPurviewDAO.count("countIsLeafBasicPurviewByFirstPurview",params);
            }else if(levelCode==2){//查看二级菜单下的三级菜单列表
                return basicPurviewDAO.count("countIsLeafBasicPurviewBySecondPurview",params);
            }
        }
        return 0;
    }

    /**
     * 查询指定节点下的所有子节点
     *
     * @param params   查询参数
     * @param startRow 起始行数（不含起始行的数据）
     * @param rowSize  要查询记录数
     * @return BASIC_权限表集合
     */
    @Override
    public List<Map<String, Object>> queryIsLeafBasicPurview(Map<String, Object> params, int startRow, int rowSize) {
        Integer parentId=Integer.parseInt(params.get("parentId").toString());
        BasicPurview bp=basicPurviewDAO.load(parentId);
        if(Utils.objectIsNotEmpty(bp)){
            Integer levelCode=bp.getLevelCode();
            if(levelCode==1){//查看一级菜单中所有的二级菜单下的三级菜单列表
                return basicPurviewDAO.query("queryIsLeafBasicPurviewByFirstPurview",params,startRow,rowSize);
            }else if(levelCode==2){//查看二级菜单下的三级菜单列表
                return basicPurviewDAO.query("queryIsLeafBasicPurviewBySecondPurview",params,startRow,rowSize);
            }
        }
        return null;
    }
}